<template>
  <el-button v-if="isDoctor" class="mb5" plain type="primary" @click="handleAdd">
    <template #icon>
      <i-ep-plus/>
    </template>
    新增
  </el-button>
  <el-button class="mb5" type="primary" @click="initOpen(visitId,patientId)">
    <template #icon>
      <i-ep-search/>
    </template>
    刷新
  </el-button>
  <el-table :border="true" :data="hisDiagnosisList" :header-cell-style="headerCellStyle"
            :stripe="true" highlight-current-row>
    <!--        <el-table-column label="西/中医诊断" width="80" :align="'center'" prop="type">-->
    <!--            <template #default="scope">-->
    <!--                <template v-if="scope.row.id && !scope.row.isEdit">-->
    <!--                    <dict-data-tag :options="dictDataMap['chinese_western_type']" :value="scope.row.type"/>-->
    <!--                </template>-->
    <!--                <template v-else>-->
    <!--                    <el-select v-model="form.type" placeholder="请选择" style="width: 100%;">-->
    <!--                        <el-option v-for=" dict in dictDataMap['chinese_western_type'] " :key="dict.dictValue"-->
    <!--                                   :label="dict.dictLabel" :value="dict.dictValue"></el-option>-->
    <!--                    </el-select>-->
    <!--                </template>-->
    <!--            </template>-->
    <!--        </el-table-column>-->
    <el-table-column :align="'center'" label="诊断类型" prop="diagnosisType" width="100">
      <template #default="scope">
        <template v-if="scope.row.id && !scope.row.isEdit">
          <dict-data-tag :options="dictDataMap['diagnosis_type']" :value="scope.row.diagnosisType"/>
        </template>
        <template v-else>
          <el-select v-model="form.diagnosisType" placeholder="请选择" style="width: 100%;">
            <el-option v-for=" dict in dictDataMap['diagnosis_type'] " :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
        </template>
      </template>
    </el-table-column>
    <el-table-column :align="'center'" label="诊断描述" prop="sort" width="130">
      <template #default="scope">
        <template v-if="scope.row.id && !scope.row.isEdit">
          <span> {{ scope.row.description }}</span>
        </template>
        <template v-else>
                    <span><el-input v-model="form.description" clearable
                                    placeholder="请输入诊断描述"/></span>
        </template>
      </template>
    </el-table-column>
    <el-table-column :align="'center'" label="入院情况" prop="diagnosisType" width="120">
      <template #default="scope">
        <template v-if="scope.row.id && !scope.row.isEdit">
          <dict-data-tag :options="dictDataMap['admission_situation_dict']"
                         :value="scope.row.situation"/>
        </template>
        <template v-else>
          <el-select v-model="form.situation" placeholder="请选择" style="width: 100%;">
            <el-option v-for=" dict in dictDataMap['admission_situation_dict'] " :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
        </template>
      </template>
    </el-table-column>
    <el-table-column :align="'center'" label="是否手术" prop="operation" width="80">
      <template #default="scope">
        <template v-if="scope.row.id && !scope.row.isEdit">
          <dict-data-tag :options="dictDataMap['sys_yes_no']" :value="scope.row.operation"/>
        </template>
        <template v-else>
          <el-select v-model="form.operation" placeholder="请选择" style="width: 100%;">
            <el-option v-for=" dict in dictDataMap['sys_yes_no'] " :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
        </template>
      </template>
    </el-table-column>
    <el-table-column :align="'center'" prop="icdName">
      <template #header>
        <span class="mr5" style="color: #ff0000">*</span>疾病名称
      </template>
      <template #default="scope">
        <template v-if="scope.row.id && !scope.row.isEdit">
          <span> {{ scope.row.icdName }}</span>
        </template>
        <el-input v-else-if="scope.row.isEdit && scope.row.isShow" v-model="form.icdName"
                  @focus="isShowItemNameFocus(scope.$index, scope.row)">
        </el-input>
        <automatic-completion v-else ref="itemAutomatic" :dict-array="dictArray" :table-body-list="tableBodyList"
                              :table-head-list="tableHeadList" :title="itemTitle"
                              :width="900"
                              style="width: 100%;" @itemNameInput="itemNameInput"
                              @rowClick="rowClick($event, scope.row)"/>
      </template>
    </el-table-column>
    <el-table-column :align="'center'" label="ICD编码" prop="icdCode" width="120">
      <template #default="scope">
        <template v-if="scope.row.id && !scope.row.isEdit">
          <span> {{ scope.row.icdCode }}</span>
        </template>
        <template v-else>
          <span> {{ form.icdCode }}</span>
        </template>
      </template>
    </el-table-column>
    <el-table-column :align="'center'" label="M码" prop="micdCode" width="120">
      <template #default="scope">
        <span style="color:#fd0101;"> {{ scope.row.micdCode }}</span>
      </template>
    </el-table-column>
    <el-table-column :align="'center'" prop="effect" width="80">
      <template #header>
        <span class="mr5" style="color: #ff0000">*</span>治疗结果
      </template>
      <template #default="scope">
        <template v-if="scope.row.id && !scope.row.isEdit">
          <dict-data-tag :options="dictDataMap['treatment_effect']" :value="scope.row.effect"/>
        </template>
        <template v-else>
          <el-select v-model="form.effect" placeholder="请选择" style="width: 100%;">
            <el-option v-for=" dict in dictDataMap['treatment_effect'] " :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
        </template>
      </template>
    </el-table-column>
    <el-table-column :align="'center'" label="病理号" prop="pathologyNo" width="100">
      <template #default="scope">
        <template v-if="scope.row.id && !scope.row.isEdit">
          <span style="color:#ffc900;"> {{ scope.row.pathologyNo }}</span>
        </template>
        <template v-else>
                    <span><el-input v-model="form.pathologyNo" clearable
                                    placeholder="请输入病理号"/></span>
        </template>
      </template>
    </el-table-column>
    <el-table-column :align="'center'" label="病理诊断" prop="pathologicDiagnosis" width="130">
      <template #default="scope">
        <template v-if="scope.row.id && !scope.row.isEdit">
          <span style="color:#ffc900;"> {{ scope.row.pathologicDiagnosis }}</span>
        </template>
        <template v-else>
                    <span><el-input v-model="form.pathologicDiagnosis" clearable
                                    placeholder="请输入病理诊断"/></span>
        </template>
      </template>
    </el-table-column>
    <el-table-column :align="'center'" label="排序" prop="sort" width="100">
      <template #default="scope">
        <template v-if="scope.row.id && !scope.row.isEdit">
          <span> {{ scope.row.sort }}</span>
        </template>
        <template v-else>
          <span><el-input v-model="form.sort" clearable placeholder="请输入排序" type="number"/></span>
        </template>
      </template>
    </el-table-column>
    <el-table-column :align="'center'" label="诊断医生" prop="diagnosisDoctor" width="99">
      <template #default="scope">
        <template v-if="scope.row.id && !scope.row.isEdit">
          <span> {{ scope.row.diagnosisDoctorName }}</span>
        </template>
        <template v-else>
          <span> {{ form.diagnosisDoctorName }}</span>
        </template>
      </template>
    </el-table-column>
    <el-table-column :align="'center'" label="诊断时间" prop="createTime" width="170">
      <template #default="scope">
        <template v-if="scope.row.id && !scope.row.isEdit">
          <span> {{ scope.row.createTime }}</span>
        </template>
        <template v-else>
          <el-date-picker v-model="form.createTime" clearable placeholder="请选择诊断时间" type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </template>
      </template>
    </el-table-column>

    <el-table-column v-if="isDoctor" :align="'center'" label="操作" width="100">
      <template #default="scope">
        <el-tooltip v-if="scope.row.id && !scope.row.isEdit" class="item" content="编辑" effect="dark"
                    placement="top">
          <el-button circle type="success" @click="handleUpdate(scope.$index, scope.row)">
            <template #icon>
              <i-ep-edit/>
            </template>
          </el-button>
        </el-tooltip>
        <el-tooltip v-else class="item" content="保存" effect="dark" placement="top">
          <el-button circle type="primary" @click="handleSave(scope.$index, scope.row)">
            <svg-icon :icon-class="'save'"/>
          </el-button>
        </el-tooltip>
        <el-tooltip class="item" content="删除" effect="dark" placement="top">
          <el-button circle type="danger" @click="handleDelete(scope.$index, scope.row)">
            <template #icon>
              <i-ep-delete/>
            </template>
          </el-button>
        </el-tooltip>
      </template>
    </el-table-column>
  </el-table>
</template>
<script lang="ts" setup>

import {useDictStoreHook} from "@/store/modules/dict"
import {useUserStoreHook} from "@/store/modules/user"
import {addHisDiagnosis, delHisDiagnosis, listHisDiagnosis, updateHisDiagnosis} from "@/api/diagnosis/hisDiagnosis"
import {getAutoHisIcd} from "@/api/base/hisDataIcd10"
import {icd10List, jsonStrInObj} from "@/utils/autoComplete"

const {proxy} = getCurrentInstance() as any;
const dictStore = useDictStoreHook()
let dictDataMap = ref(dictStore.isTypeGetData('diagnosis_type', 'chinese_western_type', 'admission_situation_dict',
  'treatment_effect', 'sys_yes_no'))
const useUserStore = useUserStoreHook()
const props = defineProps({
  visitId: {
    type: String,
    default: ""
  },
  patientId: {
    type: String,
    default: ""
  },
  orgId: {
    type: String,
    default: ""
  },
  isDoctor: {
    type: Boolean,
    default: true
  }
})

// 项目选择自动补全窗体名称
const itemTitle = ref('诊断选择')
// 项目选择自动补全表格表头
const tableHeadList = ref<any>(jsonStrInObj(icd10List))
// 项目选择自动补全表格数据
const tableBodyList = ref<any>([])
// 项目选择自动补全字典数组
const dictArray = ref(['chinese_western_type'])
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo
const itemAutomatic = ref()
const hisDiagnosisList = ref<any>([])
const form = ref<any>({
  operation: "N",
  createTime: proxy.$parseTime(new Date()),
})


function initOpen(visitId, patientId) {
  const param = {
    visitId: visitId,
    patientId: patientId,
    orgId: props.orgId,
    inoroutFlag: '1'
  }
  listHisDiagnosis(param).then((res: any) => {
    hisDiagnosisList.value = res.data
  })
}

function handleUpdate(index: number, row: any) {
  const isEditIndex = hisDiagnosisList.value.findIndex(item => {
    return item.isEdit === true
  })
  if (isEditIndex > -1) {
    return ElMessage.warning(`请先保存第${isEditIndex + 1}行诊断后再编辑其他诊断`)
  }
  hisDiagnosisList.value[index].isEdit = true
  row.isShow = true
  form.value = row
}

/** 设置全局table 表头背景色 */
function headerCellStyle(row) {
  const column = row.column
  if (column.property == 'micdCode') {
    return {"background-color": "#eaf9f2", "color": "#fd0101"};
  } else if (column.property == 'icdCode') {
    return {"background-color": "#eaf9f2", "color": "#0249ff"};
  } else if (column.property == 'pathologyNo' || column.property == 'pathologicDiagnosis') {
    return {"background-color": "#eaf9f2", "color": "#ffc900"};
  } else {
    return {"background-color": "#eaf9f2", color: "#fffff"};
  }
}

/** 项目名称自动补全检索 */
function itemNameInput(event, _value) {
  form.value.itemName = event
  getAutoHisIcdFun()
}

function getAutoHisIcdFun() {
  const param = {
    chineseWesternType: form.value.type,
    orgId: userInfo.orgId,
    itemInfo: form.value.itemName

  }
  getAutoHisIcd(param).then(res => {
    tableBodyList.value = res.data
    itemAutomatic.value.init()
  })
}

/** icd10自动补全点击事件 */
function rowClick(obj: any, row) {
  nextTick(() => {
    if (obj) {
      nextTick(() => {
        itemAutomatic.value.closePopover()
      })
      form.value.itemInfo = obj.zhongwenMingcheng
      form.value.icdName = obj.zhongwenMingcheng
      form.value.icdCode = obj.code
      form.value.orgId = obj.orgId
      form.value.type = obj.chineseWesternType
      form.value.clinicId = props.clinicId
      form.value.patientId = props.patientId
      if (obj.code.includes("M")) {
        row.micdCode = obj.code
        form.value.micdCode = obj.code
      } else {
        row.micdCode = ''
        form.value.micdCode = ''
      }
      itemAutomatic.value.closePopover()
      itemAutomatic.value.itemNameFocus();
    }
    row.isShow = true
  })
}

/**
 * 自动补全上边input获得焦点事件
 * @param _index
 * @param row
 */
function isShowItemNameFocus(_index: number, row: any) {
  row.isShow = false
  nextTick(() => {
    itemAutomatic.value.init()
    itemAutomatic.value.setItemName(form.value.icdName)
    itemAutomatic.value.focusInput()
  })
}

function handleSave(index: number, _row: any) {
  // form.value = row
  if (!form.value.icdName) {
    return ElMessage.error("请选择诊断后再保存")
  }
  if (!form.value.effect) {
    return ElMessage.error("请选择治疗效果后再保存")
  }
  // (formRef.value as any).validate(valid => {
  //     if (valid) {
  ElMessageBox.confirm('确定要保存吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    form.value.orgId = userInfo.orgId
    form.value.inoroutFlag = '1'
    form.value.visitId = props.visitId
    form.value.isUpdateDoctorId = "Y"
    hisDiagnosisList.value[index].isEdit = false
    if (form.value.id != "") {
      updateHisDiagnosis(form.value).then(() => {
        ElMessage.success("修改成功");
        initOpen(props.visitId, props.patientId)
      })
    } else {
      addHisDiagnosis(form.value).then(() => {
        ElMessage.success("保存成功");
        initOpen(props.visitId, props.patientId)
      })
    }
  }).catch(() => {
    initOpen(props.visitId, props.patientId)
  })
  // }
  // });
}

/** 新增诊断 */
function handleAdd() {
  const lastRow = hisDiagnosisList.value.length > 0 ? hisDiagnosisList.value[hisDiagnosisList.value.length - 1] : {isEdit: false}
  if (lastRow.isEdit) {
    return ElMessage.error("请保存上一条诊断后再添加")
  }
  hisDiagnosisList.value.push({
    isEdit: true,
    id: ''
  })
  form.value.createTime = proxy.$parseTime(new Date())
  form.value.type = '1'
  form.value.diagnosisType = '5'
  form.value.id = ""
  // form.value.isEdit = true
}


/** 删除按钮操作 */
function handleDelete(index: number, row: any) {
  if (row.id) {
    const _ids = row.id
    const icdName = row.icdName
    ElMessageBox.confirm('是否确认删除患者诊断名称为"' + icdName + '"的数据项？',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      delHisDiagnosis(_ids).then(() => {
        initOpen(props.visitId, props.patientId)
        ElMessage.success("删除成功");
      })
    }).catch(() => {
    })
  } else {
    hisDiagnosisList.value.splice(index, 1)
  }
}


defineExpose({
  initOpen
})
</script>
<style scoped>
</style>
